<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use PhpOffice\PhpWord\TemplateProcessor;
use App\Http\Requests\ComCheckAgainRequest;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comcheckdetail;
use App\Model\Checkentry;
use App\Model\Comcheckagain;
use App\Model\Comcheckagaindetail;
use App\Model\Checkgroup;
use App\Model\Comsafeofficer;
use App\Model\Commanager;
use App\Model\Area;
use App\User;
use App\Model\Checknegative;
use App\Model\Checkaccord;
use App\Model\Comcheckdanger;
use App\Model\Comcheckdangerdetail;
use App\Services\Export\WordChoose;
use App\Services\ImageClass;
use Illuminate\Support\Facades\DB; 
use Illuminate\Support\Facades\Storage;
use App\Services\WordcheckdataClass;

class SmallplacecheckController extends Controller
{
    protected $comCheckAgainObj;
    protected $companyClass;

    public function __construct(Comcheckagain $comcheckagain, Company $company)
    {
        $this->comCheckAgainObj = $comcheckagain;
        $this->companyClass = $company;
    }
    /*复查页面*/
    public function checkAgainIndex()
    {
        /*获取检查人员*/
        $user = Auth::user();
        
        return view('smallplacecheck.checkagainindex', array(
                'user' => $user,
                'checktime' => date('Y-m-d')
            ) 
        );
    }

    /*复查隐患页面*/
	public function checkAgain($id) 
    {  
        $company = Company::find($id);
        if(empty($company)) {
            \Session::flash('error', '公司不存在!');
            return back();
        }
        if($company['type']!=2) {
            \Session::flash('error', '公司信息错误!');
            return back();
        }
        if($company['schedule']==1) {
            \Session::flash('error', '公司还没进行初查!');
            return back();
        }
        /*获取初查信息*/
        $comcheck_where = array();
        $comcheck_where[] = array('companyId', $company['id']);
        $comcheck = Comcheck::where($comcheck_where)->first();
        if(empty($comcheck)) {
            \Session::flash('error', '请选择初查!');
            return back();
        }
        /*获取复查信息*/
        $check_again_where = array();
        $check_again_where[] = array('companyId', $company['id']);
        $com_check_again = Comcheckagain::where($check_again_where)->orderBy('checkTime','DESC')->first();
        /*获取初步检查人员*/
        $checkUser = User::where('id', $comcheck->userId)->first();
        $comcheck['checkUser'] = $checkUser;
        /*隐患列表(初查部分查完也可以查，检查复查和初查,根据初查和复查的检查时间确定读取哪些选项)*/
        $check_list_from = 'check';
        if(!empty($com_check_again)) {
          if($comcheck['updated']<$com_check_again['checkTime']) {/*选择复查结果进行复查*/
            $check_list_from = 'checkAgain';
          }
        }

        /*获取初查详情*/
        $where = array();
        $where[] = array('checkId', $comcheck->id);
        $where[] = array('status', 2);
        $where[] = array('isfire', 0);
        $checkDetails = Comcheckdetail::where($where)->get();
        if($check_list_from=='checkAgain') {/*从复查表中读取信息*/
            $where = array();
            $where[] = array('checkId', $com_check_again->id);
            $where[] = array('status', '<>', 3);
            $dangers = Comcheckagaindetail::where($where)->get();
        } else {
            $dangers = $checkDetails;
        }
        
        /*获取违规项*/
        $negativesObj = new Checknegative();
        $negatives = $negativesObj->getChecknegativeByCheckId($comcheck->id);
        $negatives = json_decode(json_encode($negatives),true);
        $negatives = array_column($negatives,NULL,'id');
        foreach($dangers as $k=>$v) {
            $num = 1;
            $dangers[$k]->negativesContentText = "";
            $checknegativeIds = array();
            /*获取初查的负面清单*/
            if($check_list_from=='checkAgain') {
                foreach($checkDetails as $key=>$val) {
                    if($val['id']==$v['checkDetailId']) {
                        $checknegativeIds = explode(',', trim($val['negatives'], ','));
                        break;
                    }
                }
            } else {
                $checknegativeIds = explode(',', trim($v['negatives'], ','));
            }
            
            if(!empty($checknegativeIds)) {
                foreach($checknegativeIds as $key=>$val) {
                    if(isset($negatives[$val])) {
                        $dangers[$k]->negativesContentText .= '（'.$num.'）'.$negatives[$val]['content'];
                        $num += 1;
                    }
                }
            }

            /*获取初查的自定义负面清单*/
            if($check_list_from=='checkAgain') { 
                if(!empty($v->entryId)) {/*检查项来自复查且非新增隐患*/
                    foreach($checkDetails as $key=>$val) {
                        if($val['id']==$v['checkDetailId']) {
                            $tmpContent = array();
                            if(!empty($val->content)) {
                                $tmpContent = explode(";", trim($val->content,";"));
                            }
                            foreach($tmpContent as $kk=>$vv) {
                                $dangers[$k]->negativesContentText .= '（'.$num.'）'.$vv;
                                $num += 1; 
                            }
                        }
                    }
                } else {/*检查项来自复查且新增隐患*/
                    /*区分复查新增隐患是初查新增隐患还是复查新增隐患*/
                    if($v['is_add']==1) {/*复查*/
                        $dangers[$k]->negativesContentText .= '（'.$num.'）'.$v['entryContent'];
                        $num += 1;
                    } else {
                        foreach($checkDetails as $key=>$val) {
                            if($val['id']==$v['checkDetailId']) {
                                if(!empty($val['contentexist'])) {
                                    $dangers[$k]->negativesContentText .= '（'.$num.'）'.$val['contentexist'];
                                    $num += 1;
                                }
                            }
                        }
                    }
                }
            } else {/*检查项来自初查*/
                if(!empty($v->entryId)) {
                    $tmpContent = array();
                    if(!empty($v->content)) {
                        $tmpContent = explode(";", trim($v->content,";"));
                    }
                    foreach($tmpContent as $kk=>$vv) {
                        $dangers[$k]->negativesContentText .= '（'.$num.'）'.$vv;
                        $num += 1; 
                    }
                } else {
                    $dangers[$k]->negativesContentText .= '（'.$num.'）'.$v['contentexist'];
                    $num += 1;
                }
            }
            
            if($check_list_from=='checkAgain') {
                if(!empty($v->content)) {
                     $dangers[$k]->negativesContentText .= '（'.$num.'）'.$v->content;
                }
            }

            /*处理隐患图片*/
            $dangers[$k]->picturesArr = array();
            if($check_list_from=='checkAgain') {/*检查项来自复查*/
                 if($v['is_add']==1) {/*复查新增隐患*/
                    if(!empty($v['dangerPictures'])) {
                        $dangers[$k]->picturesArr = explode(',', trim($v['dangerPictures'],','));
                    }
                 } else {/*读取初查隐患图片*/
                    foreach($checkDetails as $key=>$val) {
                        if($val['id']==$v['checkDetailId']) {
                            if(!empty($val['pictures'])) {
                                $dangers[$k]->picturesArr = explode(',', trim($val->pictures,','));
                            }
                        }
                    }
                 }
            } else {/*检查项来自初查则直接处理图片*/
                if(!empty($v->pictures)) {
                  $dangers[$k]->picturesArr = explode(',', trim($v->pictures,','));
                }
            } 
            
        }

        
        return view('smallplacecheck.checkagain', array(
                'company' => $company,
                'comcheck' => $comcheck,
                'dangers' => $dangers,
                'come_from' => $check_list_from
            ) 
        );
		
    }
    /*复查信息保存*/
    public function checkAgainSave(ComCheckAgainRequest $request)
    {
        $data = $request->input();
        $hideDanger = isset($data['hideDanger'])?$data['hideDanger']:array();/*隐患*/
        $newDanger = isset($data['newDanger'])?$data['newDanger']:array();
        $companyId = $data['companyId'];
        $checkData = array();
        $checkDetailData = array();
        $company = $this->companyClass->find($companyId);
        if(empty($company)) {
        	\Session::flash('error', '公司不存在!');
            return back();
        }
        if($company['type']!=2) {
        	\Session::flash('error', '公司信息错误!');
            return back();
        }
        if($company['schedule']==1) {
          \Session::flash('error', '公司还没进行初查!');
          return back();
        }
        /*验证是否已经初查*/
        $check_where = array();
        $check_where[] = array('companyId', $companyId);
        $com_check = Comcheck::where($check_where)->first();
        if(empty($com_check)) {
            \Session::flash('error', '请先选择初查!');
            return back();
        }

        /*获取最新的复查详情*/
        $check_again_where = array();
        $check_again_where[] = array('companyId', $company['id']);
        $com_check_again = Comcheckagain::where($check_again_where)->orderBy('checkTime','DESC')->first();
        
        $comcheckdetails = array();
        if(!empty($com_check_again)) {
            $where = array();
            $where[] = array('checkId', $com_check_again->id);
            $where[] = array('status', '<>', 3);
            $comcheckdetails = Comcheckagaindetail::where($where)->get();
            $comcheckdetails = json_decode(json_encode($comcheckdetails), true);
            $comcheckdetails = array_column($comcheckdetails,NULL,'id');
        }

        /*获取公司检查项分类*/
        $checkGroup = Checkgroup::where('categoryId', $company['categoryId'])->get();
        $checkGroup = json_decode(json_encode($checkGroup), true);

        $checkData['companyId'] = $companyId;
        $user = Auth::user();
        $checkData['userId'] = $user['id'];
        $checkData['checkId'] = $com_check['id'];
        $checkData['checkTime'] = time();
        $come_from = $data['come_from'];
        if($come_from=='check') {
            $checkData['from'] = 1;
        } else if($come_from=='checkAgain') {
            $checkData['from'] = 2;
        }
        /*签名转化成图片*/
        $imageObj = new ImageClass();
        $checkData['companySign'] = $imageObj->base64toimg($data['companySign']);
        $checkData['checkSign'] = $imageObj->base64toimg($data['checkSign']);
        
        /*使用事务插入*/
        DB::beginTransaction();
        try{
            $checkRes = false;
            $checkDetailRes = false;
            $checkRes = $this->comCheckAgainObj->create($checkData);
            if($checkRes!==false) {
                /*插入复查选项*/
                foreach($hideDanger as $k=>$v) {
                    $tmpArr = array();
                    $tmpArr['checkId'] = $checkRes['id'];
                    if(!empty($v['entryId'])) {
                        $tmpArr['entryId'] = $v['entryId'];
                    } else {
                        $tmpArr['entryId'] = 0;
                    }
                    $tmpArr['status'] = $v['status'];
                    $tmpArr['content'] = $v['content'][$v['status']];
                    $pictures = "";
                    $pictures = $v['pictures'][$v['status']];
                    if(!empty($pictures)) {
                        $tmpArr['pictures'] = trim($pictures,",");
                    } else {
                        $tmpArr['pictures'] = "";
                    }
                    if($come_from=='checkAgain') {/*处理检查内容，图片，复查id的保存*/
                        if(isset($v['checkAgainDetailId'])&&isset($comcheckdetails[$v['checkAgainDetailId']])) {
                            $tmpArr['checkAgainDetailId'] = $comcheckdetails[$v['checkAgainDetailId']]['id'];
                            $tmpArr['entryContent'] = $comcheckdetails[$v['checkAgainDetailId']]['entryContent'];
                            $tmpArr['dangerPictures'] = $comcheckdetails[$v['checkAgainDetailId']]['dangerPictures'];
                            $tmpArr['is_add'] = $comcheckdetails[$v['checkAgainDetailId']]['is_add'];
                        }
                    } else {/*检查项来自初查*/
                        $tmpArr['checkAgainDetailId'] = 0;
                        $tmpArr['entryContent'] = "";
                        $tmpArr['dangerPictures'] = "";
                        $tmpArr['is_add'] = 0;
                    }
                    $tmpArr['groupId'] = $v['groupId'];
                    $tmpArr['checkDetailId'] = $v['checkDetailId'];
                    
                    $tmpArr['userId'] = $user['id'];
                    $checkDetailData[] = $tmpArr;
                }

                /*处理新添加隐患*/
                foreach($newDanger as $k=>$v) {
                    $tmpArr = array();
                    $tmpArr['checkId'] = $checkRes['id'];
                    if(!empty($v['entryId'])) {
                        $tmpArr['entryId'] = $v['entryId'];
                    } else {
                        $tmpArr['entryId'] = 0;
                    }
                    if(empty($v['entryContent'])) {
                        continue;
                    }
                    $tmpArr['status'] = 0;
                    $tmpArr['content'] = "";
                    $tmpArr['entryContent'] = $v['entryContent'];
                    $tmpArr['pictures'] = "";
                    $pictures = "";
                    $pictures = $v['dangerPictures'];
                    if(!empty($pictures)) {
                        $tmpArr['dangerPictures'] = trim($pictures,",");
                    } else {
                        $tmpArr['dangerPictures'] = "";
                    }
                    $tmpType = $v['type'];
                    $tmpStatus = $v['status'];
                    foreach($checkGroup as $key=>$val) {
                        if($val['type']==$tmpType&&$val['status']==$tmpStatus) {
                            $tmpArr['groupId'] = $val['id'];
                        }
                    }
                    $tmpArr['checkDetailId'] = 0;
                    $tmpArr['is_add'] = 1;
                    $tmpArr['checkAgainDetailId'] = 0;
                    $tmpArr['userId'] = $user['id'];
                    $checkDetailData[] = $tmpArr;
                }
                $comCheckAgainDetailObj = new Comcheckagaindetail();
                $checkDetailRes = $comCheckAgainDetailObj->addAll($checkDetailData);

                /*修改公司表*/
                if($come_from=='check') {
                    $companyData = array();
                    $companyData['schedule'] = 3;
                    $company->update($companyData);
                }
                
	        }
		   	DB::commit(); 
            /*生成检查报告*/
            if($checkRes!==false&&$checkDetailRes!==false) {
               $this->exportWord($company['id'], $checkRes);  
            }
            
		}catch (\Exception $e) { 
			DB::rollBack(); 
			\Session::flash('error', $e->getMessage());
			return back();
		}
        return redirect(route('smallplace_downword',array('company'=>$company->id)));
    }
    /*复查公司搜索页面*/
    public function companyList(Request $request)
    {
        $comname = $request->input("comname");
        $company_where = array();
        if(!empty($comname)) {
        	$company_where[] = array('comName', 'like', '%'.$comname.'%');
        }
        $company_where[] = array('schedule', '>=', 2);
        $company_where[] = array('type', 2);
        $fields = array("id","comName","schedule","type");
        $companies = Company::where($company_where)->select($fields)->get();
        if(!empty($comname)) {
        	foreach($companies as $k=>$v) {
	        	$companies[$k]['comName'] = preg_replace("/($comname)/i", 
									"<font color=red><b>\\1</b></font>", 
									$v['comName']); 
	        }
        }
        
        return view('smallplacecheck.companylist', array(
                'companies' => $companies
            )
        );

    }

    /*word下载*/
    public function downWord($companyId) 
    {
        $company = $this->companyClass->select(array('id','comName'))->find($companyId);
        $comcheckagain_where = array();
        $comcheckagain_where[] = array('companyId', $company->id);
        $checkAgain = Comcheckagain::where($comcheckagain_where)->orderBy('checkTime','DESC')->first();
        if(empty($checkAgain['wordsUrl'])) {
            $wordsUrl = array();
        } else {
            $wordsUrl = explode(',', $checkAgain['wordsUrl']);
        }
        $wordsArr = array();
        foreach($wordsUrl as $k=>$v) {
            $arr = array(); 
            preg_match("/^(\/storage\/word\/)[0-9]{8}\//i",$v, $matches);
            $front = $matches[0];
            preg_match("/\_[0-9]{4}\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}\.docx$/i", $v, $matches);
            $after = $matches[0];
            $name = str_replace(array($front, $after), '', $v);
            $arr['name'] = $name;
            $arr['url'] = $v;
            $wordsArr[] = $arr;
        }
        return view('smallplacecheck.downword', array(
            'wordsArr' => $wordsArr,
            'company' => $company
            )
        );
    }

    /*生成检查报告*/
    protected function exportWord($companyId, $checkAgain)
    {
    	$company = Company::find($companyId);

        $safeuser = Comsafeofficer::where('companyId', $company->id)->first();
        /*主要负责人*/
        $manager = Commanager::where('companyId', $company->id)->first();
        /*公司地址*/
        $address = array();
        $province = Area::find($company->province)->name;
        $city = Area::find($company->city)->name;
        $district = Area::find($company->district)->name;
        $street = Area::find($company->street)->name;
        $address = array('province'=>$province, 'city'=>$city, 'district'=>$district, 'street'=>$street);
    	
        /*初查信息*/
    	$check_where = array();
    	$check_where[] = array('companyId', $companyId);
    	$check = Comcheck::where($check_where)->first();
        $checkUser = User::where('id', $check->userId)->first();
        $checkDetailObj = new Comcheckdetail();
        $checkDetails = $checkDetailObj->getInconform($check['id']);
        foreach($checkDetails as $k=>$v) {
            $checkDetails[$k]->picturesArr = array();
            if(!empty($v->pictures)) {
              $checkDetails[$k]->picturesArr = explode(',', trim($v->pictures,','));
            }
        }
    	/*复查信息*/
        $checkAgain = $this->comCheckAgainObj->find($checkAgain->id);
        $checkAgainUser = User::where('id', $checkAgain->userId)->first();
    	$checkagain_detail_where = array();
    	$checkagain_detail_where[] = array('checkId', $checkAgain['id']);
    	$checkAgainDetails = Comcheckagaindetail::where($checkagain_detail_where)->get();
        /*获取分类*/
        $check_group_where = array();
        $check_group_where[] = array('categoryId', $company['categoryId']);
        $check_group = Checkgroup::where($check_group_where)->get();
        $check_group_index = array();
        foreach($check_group as $k=>$v) {
            $check_group_index[$v['id']] = $v;
        }
        /*获取法律依据*/
        $checkAccordObj = new Checkaccord();
        $checkaccords = $checkAccordObj->getAccordByCheckAgainId($checkAgain->id);
        $checkaccords = json_decode(json_encode($checkaccords), true);
        $checkaccordsArr = array();
        foreach($checkaccords as $key=>$value) {
            $checkaccordsArr[$value['entryId']][] = $value;
        }
        /*获取负面清单*/
        $checkNegativeObj =  new Checknegative();
        $checknegatives = $checkNegativeObj->getChecknegativeByCheckId($check['id']);
        $checknegatives = json_decode(json_encode($checknegatives), true);
        $checknegatives = array_column($checknegatives,NULL,'id');
        /*关联初查和负面清单和状态*/
        foreach($checkDetails as $k=>$v) {
            $checkDetails[$k]->type = $check_group_index[$v->groupId]['type'];
            $checkDetails[$k]->group_status = $check_group_index[$v->groupId]['status'];
            $checkDetails[$k]->negativesText = '';
            $checkDetails[$k]->negativesStr = '';
            if(!empty($v->entryId)) {
                $negativeIds = explode(',', trim($v->negatives, ','));
                foreach($negativeIds as $key=>$val) {
                    if(isset($checknegatives[$val])) {
                        $checkDetails[$k]->negativesText .= '<w:br />'.$checknegatives[$val]['content'];
                        $checkDetails[$k]->negativesStr .= ','.$checknegatives[$val]['content'];
                    }
                }
                $checkDetails[$k]->negativesText = trim($checkDetails[$k]->negativesText, '<w:br />');
                $checkDetails[$k]->negativesStr = trim($checkDetails[$k]->negativesStr, ',');
            } 
        }
    	foreach($checkAgainDetails as $k=>$v) {
            /*处理初查和复查之间的关联*/
            foreach($checkDetails as $key=>$val) {
                if($v->checkDetailId==$val->detailId) {
                    $checkAgainDetails[$k]->check = $val;
                }
            }
            
            /*关联法律依据(检查点和法律依据是一对一)*/
            $checkAgainDetails[$k]->accords = "";
            if(isset($checkaccordsArr[$v['entryId']])) {
                foreach($checkaccordsArr[$v['entryId']] as $kk=>$vv) {
                    $checkAgainDetails[$k]->accords .= '<w:br />'.$vv['title'].'<w:br />'.preg_replace("/(<br\/>)/i",
                    "<w:br />",
                    $vv['content']);
                } 
                $checkAgainDetails[$k]->accords = trim($checkAgainDetails[$k]->accords,'<w:br />');
            }

            $checkAgainDetails[$k]['group_status'] = $check_group_index[$v['groupId']]['status'];
            $checkAgainDetails[$k]['type'] = $check_group_index[$v['groupId']]['type'];
            
            if(!empty($v['pictures'])) {
                $checkAgainDetails[$k]['pictureArr'] = explode(',', $v['pictures']);
            } else {
                $checkAgainDetails[$k]['pictureArr'] = array();
            }

            /*处理复查新增隐患图片*/
            $checkAgainDetails[$k]['dangerPictureArr'] = array();
            if($v['is_add']==1&&!empty($v['dangerPictures'])) {
                $checkAgainDetails[$k]['dangerPictureArr'] = explode(",", trim($v['dangerPictures'], ","));
            }
        		
    		$reformStatus = $v['status'];
    		$reformText = '';
    		if($reformStatus==1) {
    			$reformText = '未整改';
    		} else if($reformStatus==2) {
    			$reformText = '部分整改';
    		} else if($reformStatus==3) {
    			$reformText = '已整改';
    		}
            $checkAgainDetails[$k]->reformText = $reformText;

            /*分类*/
            $groupStatusText = '';
            if($check_group_index[$v['groupId']]['status']==1) {
                $groupStatusText = '管<w:br />理<w:br />档<w:br />案<w:br />类';
            } else {
                $groupStatusText = '作<w:br />业<w:br />现<w:br />场<w:br />类';
            }
        
            
            $checkAgainDetails[$k]->groupStatusText = $groupStatusText;
    	}
        /*区分消防非消防*/
        $fireArr = array();
        $unfireArr = array();
        foreach($checkAgainDetails as $k=>$v) {
            if($v->type==1) {
                $fireArr[] = $v;
            } else if($v->type==2) {
                $unfireArr[] = $v;
            }
        }

    	/*检查记录表*/
    	$exportLogData = array();
    	$exportLogData['company'] = $company['comName'];
        if(!empty($safeuser)) {
            $exportLogData['safeUser'] = $safeuser->name;
            $exportLogData['safePhone'] = $safeuser->phone;
        } else {
            $exportLogData['safeUser'] = "";
            $exportLogData['safePhone'] = "";
        }
        $exportLogData['address'] = $province.$city.$district.$street.$company->address;
        $exportLogData['checkUser'] = $checkUser->name;
        $exportLogData['checkTime'] = date('Y', strtotime($check['created'])).'年'.date('m', strtotime($check['created'])).'月'.date('d', strtotime($check['created'])).'日';
        $exportLogData['checkAgainUser'] = $checkAgainUser->name;
        $exportLogData['checkAgainTime'] = date('Y', $checkAgain['checkTime']).'年'.date('m', $checkAgain['checkTime']).'月'.date('d', $checkAgain['checkTime']).'日';
        $exportLogData['checkAgainPhone'] = $checkAgainUser->phone;
        
    	/*导出word*/
    	$templateFireProcessor =  new TemplateProcessor('./word/消防安全检查记录表-复查.docx');
        $templateUnfireProcessor = new TemplateProcessor('./word/生产安全检查记录表-复查.docx');
    	/*表格-消防*/
        $exportFireLogData = array();
        $fireAllRedirectNum = 0;
        $firePartRedirectNum = 0;
        $fireNoRedirectNum = 0;
        $fireNewDangerNum = 0;
    	foreach ($fireArr as $key => $value) {
            $tmpArr = array();
            $tmpCheck = array();
            $tmpCheck = isset($value->check)?$value->check:array();
            $tmpChekPictureArr = !empty($tmpCheck)?$tmpCheck->picturesArr:array();
            $tmpArr['num'] = $key+1;
            $tmpArr['category'] = $value['groupStatusText'];
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {/*有检查项*/
                $tmpContent = $tmpCheck->content;
                $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                $tmpArr['dagerDescription'] = trim($tmpCheck->negativesStr.','.$tmpContent,',')."。";
            } else {/*新增隐患*/
                if($value->is_add==1) {/*复查新增*/
                    $tmpArr['dagerDescription'] = $value->entryContent."。";
                } else {
                    $tmpArr['dagerDescription'] = $tmpCheck->contentexist."。";
                }
            }
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpArr['reformProposal'] = $tmpCheck->entry;
            } else {
                $tmpArr['reformProposal'] = '';
            }
            /*初查隐患图片*/
            if(!empty($tmpCheck)&&!empty($tmpChekPictureArr)) {
                $picture_arr = explode('.', $tmpChekPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['dagerPicture'] =  array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
               $tmpArr['dagerPicture'] =  "";
            }
            /*判断是否是复查新增*/
            if($value->is_add==1&&!empty($value->dangerPictureArr)) {/*复查新增*/
                $picture_arr = explode('.', $value->dangerPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['dagerPicture'] =  array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            }
            if($value->status==2) {
                $tmpArr['reformStatus'] = $value['content'];
            } else {
                $tmpArr['reformStatus'] = $value['reformText'];
            }
            
            if(!empty($value->pictureArr)) {
                $picture_arr = explode('.', $value->pictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['reformPicture'] =  array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
                $tmpArr['reformPicture'] = "";
            }
            $tmpArr['accords'] = $value['accords'];
            $tmpArr['remark'] = '';
            if($value['status']==1) {
                $fireNoRedirectNum += 1;
            } else if($value['status']==2) {
                $firePartRedirectNum += 1;
            } else if($value['status']==3) {
                $fireAllRedirectNum += 1;
            } else {
                $fireNewDangerNum += 1;
            }
            $exportFireLogData[$key+1] = $tmpArr;
        }

        $exportFireLogBasicData = array();
        $exportFireLogBasicData = $exportLogData;
        $exportFireLogBasicData['dangerNum'] = 0;
        foreach ($checkDetails as $key => $value) {
            if($value->type==1) {/*初查消防*/
                $exportFireLogBasicData['dangerNum'] += 1;
            }
        }
        $exportFireLogBasicData['allRedirectNum'] = $fireAllRedirectNum;
        $exportFireLogBasicData['partRedirectNum'] = $firePartRedirectNum;
        $exportFireLogBasicData['noRedirectNum'] = $fireNoRedirectNum;
        $exportFireLogBasicData['newDangerNum'] = $fireNewDangerNum;
        $fireTotalNum = $fireAllRedirectNum + $firePartRedirectNum + $fireNoRedirectNum;
        if($fireTotalNum > 0) {
            $exportFireLogBasicData['redirectRate'] = round(($fireAllRedirectNum/$fireTotalNum)*100,2).'%';
        } else {
             $exportFireLogBasicData['redirectRate'] = '0%';
        }
        $file = './word/'.date('Ymd', time());
        $comName = $company['comName'];
        $docFireName = $comName.'消防安全检查记录表_' . date('Y-m-d-h-i-s', $checkAgain['checkTime']);
        $wordFireClass = WordChoose::choose($templateFireProcessor,'nineCheckAgainLog');
        $wordFireClass->set($exportFireLogBasicData,$exportFireLogData);
        $wordFireUrl = $wordFireClass->create(date('Ymd', time()),$docFireName);
        /*表格-非消防*/
        $exportUnFireLogData = array();
        $unfireAllRedirectNum = 0;
        $unfirePartRedirectNum = 0;
        $unfireNoRedirectNum = 0;
        $unfireNewDangerNum = 0;
        foreach ($unfireArr as $key => $value) {
            $tmpArr = array();
            $tmpCheck = array();
            $tmpCheck = isset($value->check)?$value->check:array();
            $tmpArr['num'] = $key+1;
            $tmpArr['category'] = $value['groupStatusText'];
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) { 
                $tmpContent = $tmpCheck->content;
                $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                $tmpArr['dagerDescription'] = trim($tmpCheck->negativesStr.','.$tmpContent,',')."。";
            } else {/*新增隐患*/
                if($value->is_add==1) {/*复查新增*/
                    $tmpArr['dagerDescription'] = $value->entryContent."。";
                } else {
                    $tmpArr['dagerDescription'] = $tmpCheck->contentexist."。";
                }
            }
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpArr['reformProposal'] = $tmpCheck->entry;
            } else {
                $tmpArr['reformProposal'] = '';
            }
            /*初查隐患图片*/
            if(!empty($tmpCheck)&&!empty($tmpCheck->picturesArr)) {
                $picture_arr = explode('.', $tmpCheck->picturesArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['dagerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);;
            } else {
              $tmpArr['dagerPicture'] = "";
            }
            /*判断是否是复查新增*/
            if($value->is_add==1&&!empty($value->dangerPictureArr)) {/*复查新增*/
                $picture_arr = explode('.', $value->dangerPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['dagerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            }
            if($value['status']==2) {
                $tmpArr['reformStatus'] = $value['content'];
            } else {
                $tmpArr['reformStatus'] = $value['reformText'];
            }
            if(!empty($value->pictureArr)) {
                $picture_arr = explode('.', $value->pictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['reformPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);;
            } else {
              $tmpArr['reformPicture'] = "";
            }
            $tmpArr['accords'] = $value['accords'];
            $tmpArr['remark'] = '';
            if($value['status']==1) {
                $unfireNoRedirectNum += 1;
            } else if($value['status']==2) {
                $unfirePartRedirectNum += 1;
            } else if($value['status']==3) {
                $unfireAllRedirectNum += 1;
            } else {
                $unfireNewDangerNum += 1;
            }
            $exportUnFireLogData[$key+1] = $tmpArr;
        }

        $exportUnFireLogBasicData = array();
        $exportUnFireLogBasicData = $exportLogData;
        $exportUnFireLogBasicData['dangerNum'] = 0;
        foreach ($checkDetails as $key => $value) {
            if($value->type==2) {/*初查生产*/
                $exportUnFireLogBasicData['dangerNum'] += 1;
            }
        }
        $exportUnFireLogBasicData['allRedirectNum'] = $unfireAllRedirectNum;
        $exportUnFireLogBasicData['partRedirectNum'] = $unfirePartRedirectNum;
        $exportUnFireLogBasicData['noRedirectNum'] = $unfireNoRedirectNum;
        $exportUnFireLogBasicData['newDangerNum'] = $unfireNewDangerNum;
        $unfireTotalNum = $unfireAllRedirectNum+$unfirePartRedirectNum+$unfireNoRedirectNum;
        if($unfireTotalNum >0) {
            $exportUnFireLogBasicData['redirectRate'] = round(($unfireAllRedirectNum/$unfireTotalNum)*100,2).'%';
        } else {
            $exportUnFireLogBasicData['redirectRate'] = '0%';
        }
        
        $file = './word/'.date('Ymd', time());
        $comName = $company->comName;
        $docUnfireName = $comName.'生产安全检查记录表_' . date('Y-m-d-h-i-s', $checkAgain['checkTime']);
        $wordUnFireClass = WordChoose::choose($templateUnfireProcessor,'nineCheckAgainLog');
        $wordUnFireClass->set($exportUnFireLogBasicData,$exportUnFireLogData);
        $wordUnfireUrl = $wordUnFireClass->create(date('Ymd', time()),$docUnfireName);
        /*隐患整改告知单*/
        $fireTemplateDangerNotifyProcessor = new TemplateProcessor('./word/消防安全事故隐患整改情况告知单-复查.docx');
        $unfireTemplateDangerNotifyProcessor = new TemplateProcessor('./word/生产安全事故隐患整改情况告知单-复查.docx');
        $notifyInformation = array();
        $notifyInformationImage = array();
        $notifyInformation['entourageName'] = $company['accompany'];
        $notifyInformation['company'] = $company['comName'];
        /*消防*/
        $fireAllRedirectText = '';
        $firePartRedirectText = '';
        $fireNoRedirectText = '';
        $fireNewDangerText = '';
        $fireContentNum = 1;
        foreach($fireArr as $k=>$v) {
            $tmpCheck = array();
            $tmpCheck = isset($v->check)?$v->check:array();
            $tmpStr = "";
            if($v->status==2) {/*部分整改显示描述*/
                $tmpStr .= $v->content;
            } else {/*未修改和已经修改放负面清单*/
                if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {/*有检查项*/
                    if(!empty($tmpCheck->negativesStr)) {
                        $tmpStr .= $tmpStr?",".$tmpCheck->negativesStr:$tmpCheck->negativesStr;
                    } 
                    /*初查内容*/
                    if(!empty($tmpCheck->content)) {
                        $tmpContent = $tmpCheck->content;
                        $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                        $tmpStr .= $tmpStr?",".$tmpContent:$tmpContent;
                    }
                } else {/*新增隐患区分初查和复查*/
                     if($v->is_add==1) {/*复查*/
                        $tmpStr .= $v->entryContent;
                     } else {
                        $tmpStr .= $tmpStr?",".$tmpCheck->contentexist:$tmpCheck->contentexist;
                     }
                }
            }
            if($v->status==3) {
                $fireAllRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />"; 
            } else if($v->status==2) {
                $firePartRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";  
            } else if($v->status==1) {
                $fireNoRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";
            } else {/*新增隐患*/
                $fireNewDangerText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";
            }
            $fireContentNum += 1;
        }
        if(!empty($fireAllRedirectText)) {
            $notifyInformation['fireAllRedirect'] =  mb_substr($fireAllRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['fireAllRedirect'] = "无";
        }
        if(!empty($firePartRedirectText)) {
            $notifyInformation['firePartRedirect'] = mb_substr($firePartRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['firePartRedirect'] = "无";
        }
        if(!empty($fireNoRedirectText)) {
            $notifyInformation['fireNoRedirect'] = mb_substr($fireNoRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['fireNoRedirect'] = "无";
        }
        if(!empty($fireNewDangerText)) {
            $notifyInformation['fireNewDanger'] = mb_substr($fireNewDangerText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['fireNewDanger'] = "无";
        }
        
        /*非消防*/
        $unfireAllRedirectText = '';
        $unfirePartRedirectText = '';
        $unfireNoRedirectText = '';
        $unfireNewDangerText = '';
        $unfireContentNum = 1;
        foreach($unfireArr as $k=>$v) {
            $tmpCheck = array();
            $tmpCheck = isset($v->check)?$v->check:array();
            $tmpStr = "";
            if($v->status==2) {/*部分整改放描述*/
                $tmpStr .= $v->content;
            } else {/*未整改和已经整改放负面清单*/
                if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                    if(!empty($tmpCheck->negativesStr)) {
                        $tmpStr .= $tmpStr?",".$tmpCheck->negativesStr:$tmpCheck->negativesStr;
                    }
                    if(!empty($tmpCheck->content)) {
                        $tmpContent = $tmpCheck->content;
                        $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                        $tmpStr .= $tmpStr?",".$tmpContent:$tmpContent;
                    }
                } else {/*新增隐患区分初查和复查*/
                    if($v->is_add==1) {/*复查*/
                        $tmpStr .= $v->entryContent;
                    } else {
                        $tmpStr .= $tmpStr?",".$tmpCheck->contentexist:$tmpCheck->contentexist;
                    }
                }
                
            }
           
            if($v->status==3) {
                $unfireAllRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else if($v->status==2) {
                $unfirePartRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else if($v->status==1) {
                $unfireNoRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else {
                $unfireNewDangerText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            }
            $unfireContentNum += 1;
        }
        if(!empty($unfireAllRedirectText)) {
            $notifyInformation['UnfireAllRedirect'] =  mb_substr($unfireAllRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['UnfireAllRedirect'] = "无";
        }
        if(!empty($unfirePartRedirectText)) {
            $notifyInformation['UnfirePartRedirect'] = mb_substr($unfirePartRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['UnfirePartRedirect'] = "无";
        }
        if(!empty($unfireNoRedirectText)) {
            $notifyInformation['UnfireNoRedirect'] = mb_substr($unfireNoRedirectText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['UnfireNoRedirect'] = "无";
        }
        if(!empty($unfireNewDangerText)) {
            $notifyInformation['UnfireNewDanger'] = mb_substr($unfireNewDangerText,0,-9,'utf-8')."。";
        } else {
            $notifyInformation['UnfireNewDanger'] = "无";
        }
        $notifyInformation['leaderPhone'] = $company['leaderPhone'];
        $notifyInformation['year'] = date('Y', $checkAgain['checkTime']);
        $notifyInformation['month'] = date('m', $checkAgain['checkTime']);
        $notifyInformation['day'] = date('d', $checkAgain['checkTime']);
        $notifyInformation['checkPhone'] = $checkAgainUser->phone;

        if(!empty($checkAgain['companySign'])) {
            $notifyInformationImage['companySign'] = array('path'=>'.'.$checkAgain['companySign'],'width'=>100,'height'=>80);
        } else {
            $notifyInformationImage['companySign'] = array('path'=>'');;
        }
        if(!empty($checkAgain['checkSign'])) {
            $notifyInformationImage['checkSign'] = array('path'=>'.'.$checkAgain['checkSign'],'width'=>100,'height'=>80);
        } else {
            $notifyInformationImage['checkSign'] = array('path'=>'');
        }
          
        $file = './word/'.date('Ymd', time());
        $comName = $company['comName'];
        $fireDocName = $comName.'消防安全事故隐患整改情况告知单_' . date('Y-m-d-h-i-s', $checkAgain['checkTime']);
        $fireWordDangerNotifyClass = WordChoose::choose($fireTemplateDangerNotifyProcessor,'notice');
        $fireWordDangerNotifyClass->set($notifyInformation,$notifyInformationImage);
        $fireWordNotifyUrl = $fireWordDangerNotifyClass->create(date('Ymd', time()),$fireDocName);

        $unfireDocName = $comName.'生产安全事故隐患整改情况告知单_' . date('Y-m-d-h-i-s', $checkAgain['checkTime']);
        $unfireWordDangerNotifyClass = WordChoose::choose($unfireTemplateDangerNotifyProcessor,'notice');
        $unfireWordDangerNotifyClass->set($notifyInformation,$notifyInformationImage);
        $unfireWordNotifyUrl = $unfireWordDangerNotifyClass->create(date('Ymd', time()),$unfireDocName);

        /*安全检查档案*/
        $archivesData = $this->archives($company,$address,$manager,$check,$checkDetails,$checkAgain,$checkAgainDetails,$checkUser,$checkAgainUser);
        $checkDataClass = new WordcheckdataClass();
        $returnImg = $checkDataClass->generateCheckAgainBar($checkAgainDetails,$checkDetails);
        $archivesData['imgData'] = array_merge($archivesData['imgData'], $returnImg);
        $archivesProcessor = new TemplateProcessor('./word/安全检查档案-复查.docx');
        $archivesDocName = $comName.'安全检查档案_'. date('Y-m-d-h-i-s', $checkAgain['checkTime']);
        $archivesWordClass = WordChoose::choose($archivesProcessor,'archives');
       
        $archivesWordClass->set($archivesData['basicData'], $archivesData['imgData'], $archivesData['record']);
        $archivesWordUrl = $archivesWordClass->create(date('Ymd', time()),$archivesDocName);
        /*保存word文档路径*/
        $updateData = array();
        $url = trim($wordFireUrl,'.').','.trim($wordUnfireUrl,'.').','.trim($fireWordNotifyUrl,'.').','.trim($unfireWordNotifyUrl, '.').','.trim($archivesWordUrl, '.');
        $updateData['wordsUrl'] = $url;
        $checkAgain->update($updateData);
        return true;
    }

    protected function archives($company,$address,$manager,$check,$checkdetails,$checkagain,$checkagaindetails,$checkuser,$checkagainuser) 
    {
        $wordData = array();
        $imgData = array();
        $records = array();
        $year = date('Y', strtotime($check->created));
        $month = date('m', strtotime($check->created));
        $day = date('d', strtotime($check->created));
        $hour = date('H', strtotime($check->created));
        $againYear = date('Y', $checkagain->checkTime);
        $againMonth = date('m', $checkagain->checkTime);
        $againDay = date('d', $checkagain->checkTime);
        $againHour = date('H', $checkagain->checkTime);
        /*区分消防非消防*/
        $fireArr = array();
        $unfireArr = array();
        foreach($checkagaindetails as $k=>$v) {
            if($v->type==1) {
                $fireArr[] = $v;
            } else if($v->type==2) {
                $unfireArr[] = $v;
            }
        }
        $wordData['company'] = $company->comName;
        $wordData['checkAgainTime'] = $againYear.'年'.$againMonth.'月'.$againDay.'日';
        $wordData['address'] = $address['province'].$address['city'].$address['district'].$address['street'].$company->address;
        $wordData['space'] = $company->space;
        $wordData['floorSpace'] = $company->area;
        $wordData['workNum'] = $company->workersNum;
        $wordData['leader'] = $company->leader;
        if(!empty($company->leaderPhone)) {
            $wordData['leaderPhone'] = $company->leaderPhone;
        } else {
            $wordData['leaderPhone'] = "&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;";
        }
        $wordData['accompany'] = $company->accompany;
        
        if(!empty($manager)) {
            $wordData['manager'] = $manager->name;
            $wordData['managerPhone'] = $manager->phone;
        } else {
            $wordData['manager'] = "&#8194;&#8194;&#8194;&#8194;";
            $wordData['managerPhone'] = "&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;&#8194;";
        }
        $wordData['checkTime'] = $year.'年'.$month.'月'.$day.'日';
        $wordData['checkUser'] = $checkuser->name;
        if(!empty($company->service)) {
            $wordData['serviceUser'] = $company->service;
        } else {
            $wordData['serviceUser'] = "&#8194;&#8194;&#8194;&#8194;";
        }
        $wordData['checkPhone'] = $checkuser->phone;
        

        /*获取重大隐患数量*/
        $seriousDangerNum = 0;
        $dangerNum = 0;
        foreach($checkdetails  as $k=>$v) {
            if($v->isfire==1) {
                $seriousDangerNum += 1;
            } else {
                $dangerNum += 1;
            }
        }
        $wordData['seriousDangerNum'] = $seriousDangerNum;
        $wordData['dangerNum'] = $dangerNum;

        $wordData['fireArchivesNum'] = 0;
        $wordData['productArchivesNum'] = 0;
        $wordData['fireWorkNum'] = 0;
        $wordData['productWorkNum'] = 0;
        foreach ($checkdetails as $key => $value) {
            if($value->type==1) {/*消防*/
                if($value->group_status==1) {
                    $wordData['fireArchivesNum'] += 1;
                } else {
                    $wordData['fireWorkNum'] += 1;
                }
            } else if($value->type==2){/*生产*/
                if($value->group_status==1) {
                    $wordData['productArchivesNum'] += 1;
                } else {
                    $wordData['productWorkNum'] += 1;
                }
            }
        }
        $wordData['fireNum'] = $wordData['fireArchivesNum'] + $wordData['fireWorkNum'];
        $wordData['productNum'] = $wordData['productArchivesNum'] + $wordData['productWorkNum'];
        $wordData['total'] = $wordData['fireNum'] + $wordData['productNum'];
        $wordData['archivesNum'] = $wordData['fireArchivesNum'] + $wordData['productArchivesNum'];
        $wordData['workTotalNum'] = $wordData['fireWorkNum'] + $wordData['productWorkNum'];

        $wordData['checkAgainUser'] = $checkagainuser->name;
        $wordData['checkAgainPhone'] = $checkagainuser->phone;

        /*整改情况*/
        $wordData['fireAllRedirectNum'] = 0;
        $wordData['firePartRedirectNum'] = 0;
        $wordData['fireNoRedirectNum'] = 0;
        $wordData['fireNewDangerNum'] = 0;
        $wordData['productAllRedirectNum'] = 0;
        $wordData['productPartRedirectNum'] = 0;
        $wordData['productNoRedirectNum'] = 0;
        $wordData['productNewDangerNum'] = 0;
        foreach($fireArr as $k=>$v) {
            if($v->status==1) {
                $wordData['fireNoRedirectNum'] += 1;
            } else if($v->status==2) {
                $wordData['firePartRedirectNum'] += 1;
            } else if($v->status==3) {
                $wordData['fireAllRedirectNum'] += 1;
            } else {
                $wordData['fireNewDangerNum'] += 1;
            }
        }
        foreach($unfireArr as $k=>$v) {
            if($v->status==1) {
                $wordData['productNoRedirectNum'] += 1;
            } else if($v->status==2) {
                $wordData['productPartRedirectNum'] += 1;
            } else if($v->status==3) {
                $wordData['productAllRedirectNum'] += 1;
            } else {
                $wordData['productNewDangerNum'] += 1;
            }
        }
        $wordData['fireTotalNum'] = $wordData['fireAllRedirectNum'] + $wordData['firePartRedirectNum'] + $wordData['fireNoRedirectNum'];
        $wordData['productTotalNum'] = $wordData['productNoRedirectNum']+$wordData['productPartRedirectNum']+$wordData['productAllRedirectNum'];
        $wordData['allRedirectNum'] = $wordData['fireAllRedirectNum'] + $wordData['productAllRedirectNum'];
        $wordData['partRedirectNum'] = $wordData['firePartRedirectNum'] + $wordData['productPartRedirectNum'];
        $wordData['noRedirectNum'] = $wordData['fireNoRedirectNum'] + $wordData['productNoRedirectNum'];
        $wordData['totalNum'] = $wordData['fireTotalNum'] + $wordData['productTotalNum'];
        if($wordData['fireTotalNum'] > 0) {
            $wordData['fireRedirectRate'] = round(($wordData['fireAllRedirectNum']/$wordData['fireTotalNum'])*100,2).'%';
        } else {
            $wordData['fireRedirectRate'] = '0%';
        }
        if($wordData['productTotalNum'] > 0) {
            $wordData['productRedirectRate'] = round(($wordData['productAllRedirectNum']/$wordData['productTotalNum'])*100,2).'%';
        } else {
            $wordData['productRedirectRate'] = '0%';
        }
        if($wordData['totalNum'] > 0) {
            $wordData['totalRedirectRate'] = round(($wordData['allRedirectNum']/$wordData['totalNum'])*100,2).'%';
        } else {
            $wordData['totalRedirectRate'] = '0%';
        }
        if(!empty($check->mapimg)) {
            $imgData['map'] = array('path'=>'.'.$check->mapimg, 'width'=>567,'height'=>427);
        } else {
            $imgData['map'] = array();
        }
        if(!empty($company->photo)) {
            $imgData['photo'] = array('path'=>'.'.$company->photo, 'width'=>567,'height'=>427);
        } else {
             $imgData['photo'] = array();
        }
        if(!empty($company->license)) {
            $imgData['license'] = array('path'=>'.'.$company->license, 'width'=>614,'height'=>794);
        } else {
            $imgData['license'] = array();
        }

        /*隐患告知单*/
        $wordData['year'] = $year;
        $wordData['month'] = $month;
        $wordData['day'] = $day;
        $wordData['startHour'] = $hour;
        $wordData['endHour'] = date('H', strtotime('+1 hour',strtotime($check->created)));;
        $checkFireArr = array();
        $checkUnfireArr = array();
        foreach($checkdetails as $k=>$v) {
            if($v->type==1) {
                $checkFireArr[] = $v;
            } else if($v->type==2){
                $checkUnfireArr[] = $v;
            }
        }
        $i = 0;
        $j = 0;
        $fireArchives = '';
        $fireWork = '';
        $productArchives = '';
        $productWork = '';
        foreach ( $checkFireArr as $k => $v ) {
            if($v->group_status==1) {
                $i++;
                if(!empty($v->entryId)) {
                    $tmpContent = $v->content;
                    $tmpContent = str_replace(";", ",", trim($v->content,";"));
                    $fireArchives .= '（' . $i . '）' . trim($v->negativesStr . ',' . $tmpContent, ',') . '；<w:br />';
                } else {
                    $fireArchives .= '（' . $i . '）' . $v->contentexist . '；<w:br />';
                }
                
            }
        }
        foreach ( $checkFireArr as $k => $v ) {
            if($v->group_status==2) {
                $i++;
                if(!empty($v->entryId)) {
                    $tmpContent = $v->content;
                    $tmpContent = str_replace(";", ",", trim($v->content,";"));
                    $fireWork .= '（' . $i . '）' . trim($v->negativesStr . ',' . $tmpContent, ',') . '；<w:br />';
                } else {
                    $fireWork .= '（' . $i . '）' . $v->contentexist . '；<w:br />';
                }
                
            }
        }
        $fireArchives = mb_substr($fireArchives,0,-8,'utf-8');
        $fireWork = mb_substr($fireWork,0,-8,'utf-8');   
        if(!empty($fireArchives)&&!empty($fireWork)) {
            $fireWork = mb_substr($fireWork,0,-1,'utf-8')."。";  
        } else if(!empty($fireArchives)) {
            $fireArchives = mb_substr($fireArchives,0,-1,'utf-8')."。";
            $fireWork = '无';
        } else if(!empty($fireWork)) {
            $fireWork = mb_substr($fireWork,0,-1,'utf-8')."。";
            $fireArchives = '无';
        }

        foreach ( $checkUnfireArr as $k => $v ) {
            if($v->group_status==1) {
                $j++;
                if(!empty($v->entryId)) {
                    $tmpContent = $v->content;
                    $tmpContent = str_replace(";", ",", trim($v->content,";"));
                    $productArchives .= '（' . $j . '）' . trim($v->negativesStr . ',' . $tmpContent, ',') . '；<w:br />';
                } else {
                    $productArchives .= '（' . $j . '）' . $v->contentexist . '；<w:br />';
                } 
            }
        }
        foreach ( $checkUnfireArr as $k => $v ) {
            if($v->group_status==2) {
                $j++;
                if(!empty($v->entryId)) {
                    $tmpContent = $v->content;
                    $tmpContent = str_replace(";", ",", trim($v->content,";"));
                    $productWork .= '（' . $j . '）' . trim($v->negativesStr . ',' . $tmpContent, ',') . '；<w:br />';
                } else {
                    $productWork .= '（' . $j . '）' . $v->contentexist . '；<w:br />';
                }
                
            }
        }
        $productArchives = mb_substr($productArchives,0,-8,'utf-8');
        $productWork = mb_substr($productWork,0,-8,'utf-8');
        if(!empty($productArchives)&&!empty($productWork)) {
            $productWork = mb_substr($productWork,0,-1,'utf-8')."。";
        } else if(!empty($productArchives)) {
            $productArchives = mb_substr($productArchives,0,-1,'utf-8')."。";
            $productWork = '无';
        } else if(!empty($productWork)) {
            $productWork = mb_substr($productWork,0,-1,'utf-8')."。";
            $productArchives = '无';
        }

        $wordData['fireArchivesContent'] = $fireArchives;
        $wordData['fireWorkContent'] = $fireWork;
        $wordData['productArchivesContent'] = $productArchives;
        $wordData['productWorkContent'] = $productWork;
        $imgData['companySignature'] = array('path'=>'.'.$check->comsignature, 'width'=>120, 'height'=>80);
        $imgData['userSignature'] = array('path'=>'.'.$check->usersignature, 'width'=>120, 'height'=>80);
        

        /*隐患整改情况告知单*/
        /*消防*/
        $fireAllRedirectText = '';
        $firePartRedirectText = '';
        $fireNoRedirectText = '';
        $fireNewDangerText = '';
        $fireContentNum = 1;
        foreach($fireArr as $k=>$v) {
            $tmpCheck = array();
            $tmpCheck = isset($v->check)?$v->check:array();
            $tmpStr = "";
            if($v->status==2) {
                $tmpStr .= $tmpStr?",".$v->content:$v->content;
            } else {
                if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                    if(!empty($tmpCheck->negativesStr)) {
                        $tmpStr .= $tmpStr?",".$tmpCheck->negativesStr:$tmpCheck->negativesStr;
                    } 
                    /*初查内容*/
                    if(!empty($tmpCheck->content)) {
                        $tmpContent = $tmpCheck->content;
                        $tmpContent = str_replace(";", ",", trim($tmpCheck->content,";"));
                        $tmpStr .= $tmpStr?",".$tmpContent:$tmpContent;
                    }
                } else {
                    /*新增隐患区分初查和复查*/
                     if($v->is_add==1) {/*复查*/
                        $tmpStr .= $v->entryContent;
                     } else {
                        $tmpStr .= $tmpStr?",".$tmpCheck->contentexist:$tmpCheck->contentexist;
                     }
                }
                
            }
            if($v->status==3) { 
                $fireAllRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />"; 
            } else if($v->status==2) {
                $firePartRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";  
            } else if($v->status==1) {
                $fireNoRedirectText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";
            } else {
                $fireNewDangerText .= "（".$fireContentNum."）".$tmpStr."；<w:br />";
            }
            $fireContentNum += 1;
        }
        if(!empty($fireAllRedirectText)) {
            $wordData['fireAllRedirect'] =  mb_substr($fireAllRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['fireAllRedirect'] = "无";
        }
        if(!empty($firePartRedirectText)) {
            $wordData['firePartRedirect'] = mb_substr($firePartRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['firePartRedirect'] = "无";
        }
        if(!empty($fireNoRedirectText)) {
            $wordData['fireNoRedirect'] = mb_substr($fireNoRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['fireNoRedirect'] = "无";
        }
        if(!empty($fireNewDangerText)) {
            $wordData['fireNewDanger'] = mb_substr($fireNewDangerText,0,-9,'utf-8')."。";
        } else {
            $wordData['fireNewDanger'] = "无";
        }
        
        /*非消防*/
        $unfireAllRedirectText = '';
        $unfirePartRedirectText = '';
        $unfireNoRedirectText = '';
        $unfireNewDangerText = '';
        $unfireContentNum = 1;
        foreach($unfireArr as $k=>$v) {
            $tmpCheck = array();
            $tmpCheck = isset($v->check)?$v->check:array();
            $tmpStr = "";
            if($v->status==2) {
                if(!empty($v->content)) {
                    $tmpStr .= $tmpStr?",".$v->content:$v->content;
                }
            } else {
                if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                    if(!empty($tmpCheck->negativesStr)) {
                        $tmpStr .= $tmpStr?",".$tmpCheck->negativesStr:$tmpCheck->negativesStr;
                    }
                    if(!empty($tmpCheck->content)) {
                        $tmpContent = $tmpCheck->content;
                        $tmpContent = str_replace(";", ",", trim($tmpCheck->content,";"));
                        $tmpStr .= $tmpStr?",".$tmpContent:$tmpContent;
                    }  
                } else {/*新增隐患区分初查和复查*/
                    if($v->is_add==1) {/*复查*/
                        $tmpStr .= $v->entryContent;
                    } else {
                        $tmpStr .= $tmpStr?",".$tmpCheck->contentexist:$tmpCheck->contentexist;
                    }
                }
                
            }
            if($v->status==3) {
                $unfireAllRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else if($v->status==2) {
                $unfirePartRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else if($v->status==1) {
                $unfireNoRedirectText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            } else {
                $unfireNewDangerText .= "（".$unfireContentNum."）".$tmpStr."；<w:br />";
            }
            $unfireContentNum += 1;
        }
        if(!empty($unfireAllRedirectText)) {
            $wordData['UnfireAllRedirect'] =  mb_substr($unfireAllRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['UnfireAllRedirect'] = "无";
        }
        if(!empty($unfirePartRedirectText)) {
            $wordData['UnfirePartRedirect'] = mb_substr($unfirePartRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['UnfirePartRedirect'] = "无";
        }
        if(!empty($unfireNoRedirectText)) {
            $wordData['UnfireNoRedirect'] = mb_substr($unfireNoRedirectText,0,-9,'utf-8')."。";
        } else {
            $wordData['UnfireNoRedirect'] = "无";
        }
        if(!empty($unfireNewDangerText)) {
            $wordData['UnfireNewDanger'] = mb_substr($unfireNewDangerText,0,-9,'utf-8')."。";
        } else {
            $wordData['UnfireNewDanger'] = "无";
        }

        $wordData['againyear'] = $againYear;
        $wordData['againmonth'] = $againMonth;
        $wordData['againday'] = $againDay;

        $imgData['againCompanySignature'] = array('path'=>'.'.$checkagain->companySign, 'width'=>120, 'height'=>80);
        $imgData['againUserSignature'] = array('path'=>'.'.$checkagain->checkSign, 'width'=>120, 'height'=>80);

        /*检查记录表*/
        foreach ($fireArr as $key => $value) {
            $tmpArr = array();
            $tmpCheck = array();
            $tmpCheck = isset($value->check)?$value->check:array();
            $tmpChekPictureArr = !empty($tmpCheck)?$tmpCheck->picturesArr:array();
            $tmpArr['fireNumber'] = $key+1;
            $tmpArr['fireCategory'] = $value['groupStatusText'];
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpContent = $tmpCheck->content;
                $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                $tmpArr['fireDangerDescription'] = trim($tmpCheck->negativesText.",".$tmpContent, ",")."。";
            } else {/*新增隐患*/
                if($value->is_add==1) {/*复查新增*/
                    $tmpArr['fireDangerDescription'] = $value->entryContent."。";
                } else {
                    $tmpArr['fireDangerDescription'] = $tmpCheck->contentexist."。";
                }
            }
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpArr['fireReformProposal'] = $tmpCheck->entry;
            } else {
                $tmpArr['fireReformProposal'] = '';
            }
            /*初查隐患图片*/
            if(!empty($tmpCheck)&&!empty($tmpChekPictureArr)) {
                $picture_arr = explode('.', $tmpChekPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['fireDangerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
              $tmpArr['fireDangerPicture'] =  "";
            }
            /*判断是否是复查新增*/
            if($value->is_add==1&&!empty($value->dangerPictureArr)) {/*复查新增*/
                $picture_arr = explode('.', $value->dangerPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['fireDangerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            }
            if($value->status==2) {
                $tmpArr['fireReformStatus'] = $value->content;
            } else {
                $tmpArr['fireReformStatus'] = $value['reformText'];
            }
            if(!empty($value->pictureArr)) {
                $picture_arr = explode('.', $value->pictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['fireReformPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
              $tmpArr['fireReformPicture'] = "";
            }
            $tmpArr['fireAccords'] = $value['accords'];
            $tmpArr['fireRemark'] = '';
           
            $records['fire'][$key+1] = $tmpArr;
        }

        /*表格-非消防*/
        foreach ($unfireArr as $key => $value) {
            $tmpArr = array();
            $tmpCheck = array();
            $tmpCheck = isset($value->check)?$value->check:array();
            $tmpArr['productNumber'] = $key+1;
            $tmpArr['productCategory'] = $value['groupStatusText'];
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpContent = $tmpCheck->content;
                $tmpContent = str_replace(";", ",", trim($tmpContent,";"));
                $tmpArr['productDangerDescription'] = trim($tmpCheck->negativesText.",".$tmpContent)."。";
            } else {/*新增隐患*/
                if($value->is_add==1) {/*复查新增*/
                    $tmpArr['productDangerDescription'] = $value->entryContent."。";
                } else {
                    $tmpArr['productDangerDescription'] = $tmpCheck->contentexist."。";
                }
            }
            if(!empty($tmpCheck)&&!empty($tmpCheck->entryId)) {
                $tmpArr['productReformProposal'] = $tmpCheck->entry;
            } else {
                $tmpArr['productReformProposal'] = '';
            }
            /*初查隐患图片*/
            if(!empty($tmpCheck)&&!empty($tmpCheck->picturesArr)) {
                $picture_arr = explode('.', $tmpCheck->picturesArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['productDangerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
              $tmpArr['productDangerPicture'] = "";
            }
            /*判断是否是复查新增*/
            if($value->is_add==1&&!empty($value->dangerPictureArr)) {/*复查新增*/
                $picture_arr = explode('.', $value->dangerPictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['productDangerPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            }
            if($value->status==2) {
                $tmpArr['productReformStatus'] = $value->content;
            } else {
                $tmpArr['productReformStatus'] = $value['reformText'];
            }
            if(!empty($value->pictureArr)) {
                $picture_arr = explode('.', $value->pictureArr[0]);
                $picture_ft = $picture_arr[0].'_43.'.$picture_arr[1];
                $tmpArr['productReformPicture'] = array('path'=>'.' . $picture_ft,'width'=>151,'height'=>133);
            } else {
              $tmpArr['productReformPicture'] = "";
            }
            $tmpArr['productAccords'] = $value['accords'];
            $tmpArr['productRemark'] = '';
            $records['product'][$key+1] = $tmpArr;
        }


        $returnData = array();
        $returnData['basicData'] = $wordData;
        $returnData['imgData'] = $imgData;
        $returnData['record'] = $records;
        return $returnData;

      
    }

}
